package edu.scau.mis.web.controller.pos;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.scau.mis.core.annotation.RequestLog;
import edu.scau.mis.core.domain.AjaxResult;
import edu.scau.mis.core.enums.BusinessType;
import edu.scau.mis.pos.domain.Category;
import edu.scau.mis.pos.domain.ProductDescription;
import edu.scau.mis.pos.service.ICategoryService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    @RequestLog(title = "根据类别Id寻找类别",businessType = BusinessType.GET)
    @GetMapping("/{categoryId}")
    @ApiOperation("根据类别Id寻找类别")
    public AjaxResult getById(@PathVariable("categoryId") Long categoryId){
        return AjaxResult.success(categoryService.getCategoryById(categoryId));
    }

    @RequestLog(title = "列出所有类别",businessType = BusinessType.GET)
    @GetMapping("/listAll")
    @ApiOperation("列出所有类别")
    public AjaxResult listAll(){
        return AjaxResult.success(categoryService.listAllCategory());
    }

    @RequestLog(title = "根据id和name得到类别",businessType = BusinessType.GET)
    @GetMapping("/find")
    @ApiOperation("根据id和name得到类别")
    public AjaxResult findCategoryByIdAndName(@RequestParam(value="categoryId") Long categoryId, @RequestParam(value="categoryName") String categoryName){
        return AjaxResult.success(categoryService.findCategoryByIdAndName(categoryId,categoryName));
    }

    @RequestLog(title = "分页查询类别列表",businessType = BusinessType.GET)
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize, Category category) {
        PageHelper.startPage(pageNum,pageSize);
        List<Category> list = categoryService.selectCategoryList(category);
        PageInfo<List> pageInfo = new PageInfo(list);
        // 以下写法也可以
        // PageInfo<Category> pageInfo = new PageInfo<>(list)
        return AjaxResult.success(pageInfo);
    }

    @RequestLog(title = "新增类别",businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增类别")
    public AjaxResult add(@RequestBody Category category) {
        int rows = categoryService.insertCategory(category);
        return rows > 0 ? AjaxResult.success("添加产品类别类别成功") : AjaxResult.error("添加产品类别失败");
    }

    @RequestLog(title = "修改类别",businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改产品类别")
    public AjaxResult edit(@RequestBody Category category) {
        int rows = categoryService.updateCategory(category);
        return rows > 0 ? AjaxResult.success("修改产品类别成功") : AjaxResult.error("修改产品类别失败");
    }

    @RequestLog(title = "删除类别",businessType = BusinessType.DELETE)
    @DeleteMapping("/{categoryId}")
    @ApiOperation("批量删除产品类别")
    public AjaxResult remove(@PathVariable Long[] categoryId) {
        int rows = categoryService.deleteCategoriesByIds(categoryId);
        return rows > 0 ? AjaxResult.success("批量删除产品类别成功") : AjaxResult.error("删除产品类别失败");
    }

    /**
     * Excel批量导出数据
     */
    @RequestLog(title = "Excel批量导出数据",businessType = BusinessType.OTHER)
    @GetMapping("/export")
    @ApiOperation("Excel批量导出数据")
    public void exportData(@RequestParam(required = false) String categoryName,
                           HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 第一种全部导出
        List<Category> list = new ArrayList<>();
        if (StrUtil.isBlank(categoryName)) {
            list = categoryService.listAllCategory(); //查询出表的所有数据
        }
        //获取所有数据对象
        writer.write(list,true);

        response.setContentType("application/vnd.openxmlformats-officedocunment.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("类别信息表","UTF-8")+".xlsx");

        ServletOutputStream outputStream = response.getOutputStream();
        //刷新到输出流,写完后关闭流
        writer.flush(outputStream,true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }

    /**
     * Excel批量导入数据
     * */
    @RequestLog(title = "Excel批量导入数据",businessType = BusinessType.OTHER)
    @PostMapping("/excel/upload")
    @ApiOperation("Excel批量导入数据")
    public AjaxResult upload(MultipartFile file) throws IOException{
        List<Category> infoList = ExcelUtil.getReader(file.getInputStream()).readAll(Category.class);
        if(!CollectionUtil.isEmpty(infoList)){
            for(Category category : infoList) {
                try {
                    categoryService.insertCategory(category);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        return AjaxResult.success("上传成功");
    }
}
